import { useEffect, useState } from 'react';
import { View, Text, Image, Video } from '@tarojs/components';
import { AtIcon } from 'taro-ui';
import cssModule from './index.module.scss';
import Taro from '@tarojs/taro';


/**
 * @description 上传文件
 * @author Shawn
 */

interface FileItem {
  url: string;
  type: string;
  fileName?: string;
}

interface UploadFileProps {
  type?: 'upload' | 'view';
  count?: number;
  initialUrls?: FileItem[];
  success?: (data: string[]) => void
}

export default function SimpleUploadFile({ type = 'upload', count = 1, initialUrls, success }: UploadFileProps) {
  const [files, setFiles] = useState<FileItem[]>(initialUrls ? initialUrls.map(item => ({ url: item.url, type: item.type, fileName: item.fileName })) : []);

  const compressVideo = async (path: string) => {
    const res = await Taro.compressVideo({
      src: path,
      quality: 'medium',
      bitrate: 1032,
      fps: 24,
      resolution: 0.5,
    })
    return res.tempFilePath
  }

  const compressImage = async (path) => {
    const res = await Taro.compressImage({
      src: path, // 图片路径
      quality: 80 // 压缩质量
    })
    return res.tempFilePath
  }

  const handleAddFile = (i) => {
    return async (e) => {
      const openToken = Taro.getStorageSync('openToken');
      const res = await Taro.chooseMedia({
        count: 6 - files.length,
        sourceType: ['album', 'camera'], // 仅从相册选择
      })
      Taro.showToast({
        title: '上传中...',
        icon: 'none'
      })
      let newFiles: FileItem[] = []
      for (const file of res.tempFiles) {
        let path = file.tempFilePath
        if (file.fileType === 'image' && file.size > 20 * 1024 * 1024) {
          Taro.showToast({
            title: '图片不能超过20MB',
            icon: 'none'
          })
          break
        } else if (file.fileType === 'video' && file.size > 100 * 1024 * 1024) {
          Taro.showToast({
            title: '视频不能超过100MB',
            icon: 'none'
          })
          break
        }
        if (res.type === 'video') {
          path = await compressVideo(path)
        }
        if (res.type === 'image') {
          path = await compressImage(path)
        }
        if (path) {
          const uploadRes = await Taro.uploadFile({
            url: `https://baoyouqun.cn/api/files/upload?bucket=`,
            filePath: path,
            name: 'file',
            header: {
              cookie: `satoken=${openToken}`,
              'content-type': 'multipart/form-data'
            }
          })
          const data = JSON.parse(uploadRes.data)
          newFiles.push(
            { url: data.fileUrl, type: data.fileType, fileName: data.originalFileName }
          )
        }
        let finalNewFiles: FileItem[] = []
        if (i === -1) {
          finalNewFiles = [...files, ...newFiles]
        } else {
          finalNewFiles = [...files.slice(0, i), ...newFiles, ...files.slice(i + 1)]
        }

        setFiles(finalNewFiles);

        if (success) {
          await success(finalNewFiles.map(item => item.url))
        }

        // let path = res.tempFiles[0].tempFilePath
        // if (res.type === 'video') {
        //   path = await compressVideo(path)
        // }
        // if (res.type === 'image') {
        //   path = await compressImage(path)
        // }
        // if (path) {
        //   const uploadRes = await Taro.uploadFile({
        //     url: `https://baoyouqun.cn/api/files/upload?bucket=`,
        //     filePath: path,
        //     name: 'file',
        //     header: {
        //       cookie: `satoken=${openToken}`,
        //       'content-type': 'multipart/form-data'
        //     }
        //   })
        // const data = JSON.parse(uploadRes.data)
        // let newFiles: FileItem[] = []
        // if (i < 0) {
        //   newFiles = [...files, { url: data.fileUrl, type: data.fileType, fileName: data.originalFileName }];
        // } else {
        //   newFiles = [...files]
        //   newFiles[i] = { url: data.fileUrl, type: data.fileType, fileName: data.originalFileName }

        // }
        // console.log(newFiles, 'newFiles')
        // setFiles(newFiles);
        if (success) {
          await success(newFiles.map(item => item.url))
        }
      }
    }
  }

  const onRemoveFile = (i) => {
    return () => {
      const newFiles = files.filter((_, index) => index !== i);
      setFiles(newFiles);
      if (success) {
        success(newFiles.map(item => item.url))
      }
    }
  }

  useEffect(() => {
    setFiles(initialUrls ? initialUrls.map(item => ({ url: item.url, type: item.type, fileName: item.fileName })) : [])
  }, [initialUrls])

  return (
    <View className={cssModule.container}>
      {
        count && count > 1 && <View className={cssModule.title}>
          <Text>上传附件（最多{count}张）</Text>
        </View>
      }
      <View className={cssModule.uploadContainer}>

        {
          files.map((file, index) => (
            <View className={cssModule.fileItem} key={file.url + index}>
              {type === 'upload' && <View onClick={onRemoveFile(index)}>
                <AtIcon value='close-circle' className={cssModule.close} size='20' color='#4E5969' ></AtIcon></View>}
              {file.type && file.type.includes('image') ? (
                <View className={cssModule.uploaded}>
                  <Image className={cssModule.image} src={file.url} mode='heightFix' onClick={handleAddFile(index)} />
                </View>
              ) : file.type && file.type.includes('video') ? (
                <View className={cssModule.uploaded}>
                  <Video className={cssModule.image} src={file.url} controls={false} showFullscreenBtn={false} showCenterPlayBtn={false} onClick={handleAddFile(index)}></Video>
                </View>
              ) : (
                <View className={cssModule.uploaded} onClick={handleAddFile(index)}>
                  <Image className={cssModule.image} src='https://baoyouqun.cn/files/static/images/file_03.png' mode='heightFix' />
                </View>
              )}
            </View>
          ))
        }
        {type === 'upload' && files.length < count && <View className={cssModule.upload} onClick={handleAddFile(-1)}>
          <AtIcon value='add' size='30' color='#4E5969'></AtIcon>
        </View>}

      </View>

    </View>
  );
}
